package com.chinatelecom.ifree.business.dao.order.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.springframework.stereotype.Repository;

import com.chinatelecom.ifree.business.dao.base.DbcpPool;
import com.chinatelecom.ifree.business.dao.order.SystemConfigDao;
import com.chinatelecom.ifree.business.domain.order.SystemConfig;

@Repository
public class SystemConfigDaoImpl extends BaseDaoSupport<SystemConfig> implements SystemConfigDao {

	@Override
	public SystemConfig getSystemConfigByKey(String sysKey) throws Exception {
		sql = "SELECT * FROM sys_config where sys_key=?";
		return super.getEntityByPK(sysKey);
	}

	@Override
	public SystemConfig executeSingleResultSet(ResultSet rs) throws Exception {
		SystemConfig sysConfig = null;
		if (rs.next()) {
			sysConfig = new SystemConfig();
			sysConfig.setSysKey(rs.getString("sys_key"));
			sysConfig.setContent(rs.getString("content"));
		}
		return sysConfig;
	}

	@Override
	public boolean updateAppendSystemConfig(String pk, String content) throws Exception {
		Connection conn = null;
		PreparedStatement statement = null;
		try {
			SystemConfig config = getSystemConfigByKey(pk);
			content = content.concat(";").concat(config.getContent());
			String sql = "UPDATE sys_config SET content=? where sys_key=?";
			conn = DbcpPool.getInstance().getConn();
			statement = conn.prepareStatement(sql);
			statement.setString(1, content);
			statement.setString(2, pk);
			return statement.executeUpdate() > 0;
		} catch (Exception e) {
			throw e;
		} finally {
			DbcpPool.getInstance().closeConnection(statement, conn);
		}
	}

	@Override
	public boolean updateSystemConfig(String pk, String content) throws Exception {
		Connection conn = null;
		PreparedStatement statement = null;
		try {
			String sql = "UPDATE sys_config SET content=? where sys_key=?";
			conn = DbcpPool.getInstance().getConn();
			statement = conn.prepareStatement(sql);
			statement.setString(1, content);
			statement.setString(2, pk);
			return statement.executeUpdate() > 0;
		} catch (Exception e) {
			throw e;
		} finally {
			DbcpPool.getInstance().closeConnection(statement, conn);
		}
	}

	@Override
	public boolean addOrUpdateSystemConfig(String pk, String content) throws Exception {
		SystemConfig sysConfig = getSystemConfigByKey(pk);
		if (sysConfig != null) {
			// update
			updateSystemConfig(pk, content);
		} else {
			// insert
			SystemConfig config = new SystemConfig();
			config.setSysKey(pk);
			config.setContent(content);
			sql = "INSERT INTO sys_config (sys_key,content) values (?,?)";
			super.saveEntity(config);
		}
		return true;
	}

	@Override
	public void executeSql(PreparedStatement state, SystemConfig t) throws Exception {
		state.setString(1, t.getSysKey());
		state.setString(2, t.getContent());
	}

	@Override
	public void executeBatchSql(PreparedStatement state, SystemConfig[] t) throws Exception {
		// TODO Auto-generated method stub

	}
}
